import { AxiosRequestConfig, AxiosPromise } from "../types/index";
import xhr from "./xhr";
import {buildUrl, combineURL, isAbsoluteURL} from "../helpers/url";
import {flatterHeaders} from "../helpers/headers";
import { AxiosResponse } from "../types/index";
import transform from "./transform";

export default function  dispatchRequest(config: AxiosRequestConfig): AxiosPromise{

    throwIfCancellationRequest(config)
    processConfig(config)
    return  xhr(config).then(res=>{
        return tranformResponseData(res)
    })

}

function processConfig(config: AxiosRequestConfig): void{
    config.url = transformURL(config)
    // config.headers = transformHeader(config)
    config.data = transform(config.data, config.headers, config.transformRequest)
    config.headers = flatterHeaders(config.headers, config.method!)
}

export function transformURL(config: AxiosRequestConfig): string{
    let {url, params, paramsSerialzer, baseURL} = config
    if(baseURL && !isAbsoluteURL(url!)){
        url = combineURL(baseURL, url)
    }
    return buildUrl(url!, params, paramsSerialzer)
}


function tranformResponseData(res: AxiosResponse): AxiosResponse{
    res.data = transform(res.data, res.headers, res.config.transformResponse)
    return res
}

function throwIfCancellationRequest(config: AxiosRequestConfig): void{
    if(config.CancelToken){
        config.CancelToken.throwIfRequest()
    }
}

// export interface AxiosError extends Error{
//     isAxiosError: boolean
//     config: AxiosRequestConfig
//     code?: string | null
//     request?: any
//     response?: AxiosResponse
// }